const {
    Mysql,
    validateParams
} = require('../tools');
const uuid = require('uuid/v4')
module.exports = async ctx => {
    let {
        userInfo
    } = ctx.request.body;
    try {
        userInfo = JSON.parse(userInfo);
        if (userInfo.openid && userInfo.headimgurl) {
            let sql1 = `SELECT * FROM userInfo WHERE open_id = '${userInfo.openid}'`;
            let ourUser = await Mysql(sql1);
            if (ourUser.length) {
                if (ourUser[0].uid) {
                    ctx.state.data = {
                        data: {
                            userInfo: ourUser[0]

                        },
                        code: '001',
                    }
                } else {
                    let uid = Math.random().toString().slice(4, 10);
                    if (uid[0] == 0) {
                        start = Math.floor(Math.random() * (9 - 1)) + 1;
                        uid = `${start}${uid.substr(1,6)}`;
                    };
                    let sql = `SELECT * from userInfo WHERE uid='${uid}'`
                    let haveUserId = await Mysql(sql);
                    if (!haveUserId[0]) {
                        let sql = `UPDATE userInfo SET uid = ${uid} WHERE open_id='${userInfo.openid}'`;
                        await Mysql(sql);
                        ctx.state.data = {
                            userInfo: {
                                ...ourUser[0],
                                uid
                            },
                            code: '001'
                        }
                    }
                }
            } else {
                let uid = Math.random().toString().slice(4, 10);
                if (uid[0] == 0) {
                    start = Math.floor(Math.random() * (9 - 1)) + 1;
                    uid = `${start}${uid.substr(1,6)}`;
                };
                let sql =
                    `INSERT INTO userInfo (open_id, uuid, user_info, uid) VALUES('${userInfo.openid}','${uuid().replace('-','')}','${JSON.stringify(userInfo)}',${uid})`;
                    try {
                    await Mysql(sql);
                    ctx.state.data = {
                        data: {
                            userInfo: {
                                ...userInfo,
                                uid
                            }
                        },
                        code: '001'
                    }
                } catch (error) {
                    ctx.state.data = {
                        msg: 'ئۇچۇرىڭىزدا خاتالىق بار',
                        code: '002'
                    }
                }
            }

        } else {
            ctx.state.data = {
                msg: 'ئۇچۇرىڭىزدا خاتالىق بار',
                code: '002'
            }
        }
    } catch (error) {
        ctx.state.data = {
            msg: 'ئۇچۇرىڭىزدا خاتالىق بار',
            code: '002'
        }
    }
}